
#include "widget.h"
#include "ui_widget.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QTextCodec>
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlError>
#include <QLineEdit>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    initDB();
    loadSettings();  // 加载设置
    tcpServer = new QTcpServer(this);
    tcpSocket = new QTcpSocket(this);

    connect(tcpServer, &QTcpServer::newConnection, this, &Widget::newConnection_Slot);

    setFixedSize(480, 640);
    ui->portEdit->setText("8088");
    ui->ipED->setText("192.168.50.106");

    // 初始化 QComboBox
    // initializeComboBox(ui->mincomboBox, {"0", "500", "1000", "1500", "2000"});
    // initializeComboBox(ui->maxcomboBox, {"2500", "3000", "3500", "4000","5000"});
    // initializeComboBox(ui->mincomboBox_3, {"0", "5", "10", "15", "20"});
    // initializeComboBox(ui->maxcomboBox_4, {"20", "25", "30"});
    // initializeComboBox(ui->mincomboBox_7, {"0", "20", "40"});
    // initializeComboBox(ui->maxcomboBox_8, {"60", "80", "100"});


}

void Widget::initDB() {
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("settings.db");  // 设置数据库文件名
    if (!db.open()) {
        qDebug() << "Database error: " << db.lastError().text();
    } else {
        qDebug() << "Database connected";

        // 执行 SQL 创建表代码
        QSqlQuery query(db);
        query.exec("CREATE TABLE IF NOT EXISTS settings ("
                   "id INTEGER PRIMARY KEY,"
                   "minLight INTEGER,"
                   "maxLight INTEGER,"
                   "minTemp INTEGER,"
                   "maxTemp INTEGER,"
                   "minHumidity INTEGER,"
                   "maxHumidity INTEGER"
                   ")");
    }
}

void Widget::storeSettings(int minLight, int maxLight, int minTemp, int maxTemp, int minHumidity, int maxHumidity) {
    QSqlQuery query(db);
    query.prepare("INSERT INTO settings (minLight, maxLight, minTemp, maxTemp, minHumidity, maxHumidity) VALUES (:minLight, :maxLight, :minTemp, :maxTemp, :minHumidity, :maxHumidity)");
    query.bindValue(":minLight", minLight);
    query.bindValue(":maxLight", maxLight);
    query.bindValue(":minTemp", minTemp);
    query.bindValue(":maxTemp", maxTemp);
    query.bindValue(":minHumidity", minHumidity);
    query.bindValue(":maxHumidity", maxHumidity);
    if (!query.exec()) {
        qDebug() << "Error storing settings:" << query.lastError();
    }
}

void Widget::loadSettings() {
    QSqlQuery query(db);
    query.exec("SELECT minLight, maxLight, minTemp, maxTemp, minHumidity, maxHumidity FROM settings");
    if (query.next()) {
        int minLight = query.value(0).toInt();
        int maxLight = query.value(1).toInt();
        int minTemp = query.value(2).toInt();
        int maxTemp = query.value(3).toInt();
        int minHumidity = query.value(4).toInt();
        int maxHumidity = query.value(5).toInt();

        // 设置 QComboBox 的选中项
        ui->mincomboBox->setCurrentText(QString::number(minLight));
        ui->maxcomboBox->setCurrentText(QString::number(maxLight));
        ui->mincomboBox_3->setCurrentText(QString::number(minTemp));
        ui->maxcomboBox_4->setCurrentText(QString::number(maxTemp));
        ui->mincomboBox_7->setCurrentText(QString::number(minHumidity));
        ui->maxcomboBox_8->setCurrentText(QString::number(maxHumidity));
    }
}



Widget::~Widget()
{
    delete ui;
}

void Widget::newConnection_Slot() {
    tcpSocket = tcpServer->nextPendingConnection();
    connect(tcpSocket, &QTcpSocket::readyRead, this, &Widget::readyRead_Slot);
    connect(tcpSocket, &QTcpSocket::disconnected, this, &Widget::disconnected_Slot);

    ui->label_3->setStyleSheet("border-image: url(:/TcpServer/icons/connect.png)");
}

void Widget::disconnected_Slot() {
    tcpSocket->close();
    ui->label_3->setStyleSheet("border-image: url(:/TcpServer/icons/discon.png)");
}

void Widget::readyRead_Slot() {
    QByteArray receiveData;
    QTextCodec *tc = QTextCodec::codecForName("GBK");

    while (!tcpSocket->atEnd()) {
        receiveData = tcpSocket->readAll();
    }

    if (!receiveData.isEmpty()) {
        QString strBuf = tc->toUnicode(receiveData);
        ui->RecvEdit->appendPlainText(strBuf);
    }
    receiveData.clear();
}

void Widget::on_openBt_clicked() {
    flag_Sw = !flag_Sw;
    if (flag_Sw) {
        if (MS) {
            tcpServer->listen(QHostAddress::Any, ui->portEdit->text().toUInt());
        } else {
            tcpSocket->connectToHost(ui->ipED->text(), ui->portEdit->text().toUInt());
            connect(tcpSocket, &QTcpSocket::connected, this, &Widget::connected_Slot);
        }
        ui->openBt->setStyleSheet("border-image: url(:/TcpServer/icons/open.png)");
        ui->wifi->setStyleSheet("border-image: url(:/TcpServer/icons/wifi_on.png)");
    } else {
        tcpServer->close();
        tcpSocket->close();
        ui->openBt->setStyleSheet("border-image: url(:/TcpServer/icons/close.png)");
        ui->wifi->setStyleSheet("border-image: url(:/TcpServer/icons/wifi_off.png)");
    }
}

void Widget::on_sendBt_clicked() {
    QString SendCon = ui->sendEdit->text();

    if (flag_Sw) {
        if (!SendCon.isEmpty()) {
            QTextCodec *tc = QTextCodec::codecForName("GBK");
            QByteArray sendData = tc->fromUnicode(SendCon);

            QString str = "-> " + SendCon;
            ui->RecvEdit->appendPlainText(str);

            tcpSocket->write(sendData);
        } else {
            QMessageBox::critical(this, "警告", "不能发送空白信息");
        }
    } else {
        QMessageBox::critical(this, "提示", "发送失败，网络尚未连接");
    }
}

void Widget::on_clearBt_clicked() {
    ui->RecvEdit->clear();
}

void Widget::on_ms_clicked() {
    if (!flag_Sw) {
        tcpServer->close();
        tcpSocket->close();

        if (MS) {
            MS = false;
            ui->label->setText("客户机模式");
            ui->ms->setStyleSheet("border-image: url(:/TcpServer/icons/client.png);");
        } else {
            MS = true;
            ui->label->setText("主机模式");
            ui->ms->setStyleSheet("border-image: url(:/TcpServer/icons/server.png);");
        }
    } else {
        QMessageBox::critical(this, "提示", "请先关闭网络，再切换模式类型");
    }
}
void Widget::connected_Slot()
{
    ui->label_3->setStyleSheet("border-image: url(:/TcpServer/icons/connect.png)");
}



